<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-打包报工`"
		width="1380px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form
			ref="ruleForm"
			:model="ruleForm"
			:rules="rules"
			:hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1"
			label-width="110px"
			:show-message="false"
		>
			<div ref="box1">
				<jk-card>
					<el-row class="flex-start-center-wrap">
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
								<span class="read-only-2">{{ ruleForm.workshopName }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="生产日期" prop="belongDate">
								<span
									v-if="pageType === 'detail' || ruleForm.auditState === 1 || dataId"
									class="read-only-2"
								>{{ ruleForm.belongDate }}</span>
								<jk-date-picker
									v-else
									v-model="ruleForm.belongDate"
									:clearable="false"
									size="medium"
									placeholder=""
									@change="onDateChange"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="报工班次" prop="scheduleShiftId">
								<span
									v-if="pageType === 'detail' || ruleForm.auditState === 1 || dataId"
									class="read-only-2"
								>{{ ruleForm.shiftName }}</span>
								<el-select
									v-else
									v-model="ruleForm.scheduleShiftId"
									:disabled="!!ruleForm.id"
									clearable
									placeholder="报工班次"
									class="width-100-percent"
									@change="onScheduleShiftChange"
								>
									<el-option
										v-for="item in scheduleShiftList"
										:key="item.id"
										:label="`${item.shiftName} (${item.beginTime} ~ ${item.endTime})`"
										:value="item.id"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="报工时间">
								<span class="read-only-2">{{ ruleForm.auditTime || ruleForm.updateTime }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="18">
							<el-form-item class="margin-bottom-0" label="备注">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{
									ruleForm.remark
								}}</span>
								<el-input v-else v-model="ruleForm.remark" :rows="1" type="textarea" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-0" label="总件数">
								<span class="read-only-2">{{ totalNum || 0 }}</span>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
				<div class="margin-top-10 margin-bottom-4 flex-between-center">
					<el-tag effect="plain">
						<span class="el-icon-tickets item-gap"></span>
						<span>品种明细</span>
					</el-tag>
					<el-row>
						<el-col :span="8">
							<div style="display: flex; align-items: center;justify-content: center; width: 100px">
								<div style="width: 20px; height: 20px; border-radius: 50px; background-color: #ff4949"></div><div style="padding: 0 0 0 5px">生产订单</div>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="display: flex; align-items: center;justify-content: center; width: 100px">
								<div style="width: 20px; height: 20px; border-radius: 50px; background-color: #ff9900"></div><div style="padding: 0 0 0 5px">改包装知单</div>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="display: flex; align-items: center;justify-content: center; width: 100px">
								<div style="width: 20px; height: 20px; border-radius: 50px; background-color: #42d885"></div><div style="padding: 0 0 0 5px">包装返工单</div>
							</div>
						</el-col>
					</el-row>
					<div class="flex-start-center">
						<el-popconfirm title="确定导出吗？" @confirm="onReportBtn">
							<el-button
								slot="reference"
								:disabled="!ruleForm.itemList || !ruleForm.itemList.length || pageType === 'edit' || pageType === 'add'"
								type="warning"
								class="item-gap"
								size="mini"
							>导出
							</el-button>
						</el-popconfirm>
						<jk-button
							:disabled="!ruleForm.shiftId"
							size="mini"
							type="primary"
							icon="el-icon-refresh"
							:loading="updateLoading"
							@click="getPackageRecordListRequest"
						>更新
						</jk-button>
					</div>
				</div>
			</div>
			<jk-table
				ref="jkTable"
				:show-footer="true"
				border
				:data="ruleForm.itemList"
				:height="dialogTableHeight - 20"
				:footer-method="footerMethod"
				:span-method="mergeColMethod"
			>
				<vxe-column title="机台" align="left" field="machineName" :width="80">
					<template #header>
						<span v-if="pageType === 'detail'" slot="reference">机台</span>
						<div class="flex-center">
							<el-popover trigger="click">
								<jk-select
									v-model="selectMachineId"
									:option-list="machineList"
									placeholder="请选择机台"
									size="mini"
									icon="el-icon-plus"
									@change="onSelectMachineChange"
								></jk-select>
								<el-button v-if="pageType !== 'detail'" slot="reference" type="text" size="mini"><span
									class="el-icon-plus"
								></span>机台
								</el-button>
							</el-popover>
						</div>
					</template>
					<template slot-scope="scope">
						<div class="flex-center" style="flex-direction: column;">
							<span class="item-gap">{{ scope.row.machineName }}</span>
						</div>
						<el-popover title="数据来源" content="" placement="bottom" trigger="click">
							<div slot="reference" class="drag-info-icon" style="color: #2d8cf0;font-size: 13px;">
								<jk-button v-if="pageType !== 'detail'" icon="el-icon-plus" size="mini"></jk-button>
							</div>
							<div style="display:flex; justify-content: center; align-items: center; margin-right: 5px;">
								<jk-button v-if="pageType !== 'detail'" size="mini" style="margin-right: 5px;" type="danger" @click="onSelectBatchCodeBtn(scope, 0)">生产订单</jk-button>
								<jk-button v-if="pageType !== 'detail'" size="mini" style="margin-right: 5px;" type="warning" @click="onSelectChangeNoticeBtn(scope, 0)">改包装通知单</jk-button>
								<jk-button v-if="pageType !== 'detail'" size="mini" style="margin-right: 5px;" type="success" @click="onSelectReworkNoticeBtn(scope, 0)">包装返工单</jk-button>
							</div>
						</el-popover>
					</template>
				</vxe-column>
				<vxe-column title="品种" align="left" field="productName" :min-width="130">
					<template slot-scope="scope">
						<div class="flex-between-center">
							<div style="display: flex">
								<repair-state-bar :status="scope.row.type"></repair-state-bar>
								<span>{{ scope.row.productName }}</span>
							</div>
							<el-popover title="数据来源" content="" placement="bottom" trigger="click">
								<div slot="reference" class="drag-info-icon" style="color: #2d8cf0;font-size: 13px;">
									<div v-if="pageType !== 'detail'" class="el-icon-edit-outline operation-style"></div>
								</div>
								<div style="display:flex; justify-content: center; align-items: center; margin-right: 5px;">
									<jk-button v-if="pageType !== 'detail'" size="mini" style="margin-right: 5px;" type="danger" @click="onSelectBatchCodeBtn(scope, 1)">生产订单</jk-button>
									<jk-button v-if="pageType !== 'detail'" size="mini" style="margin-right: 5px;" type="warning" @click="onSelectChangeNoticeBtn(scope, 1)">改包装通知单</jk-button>
									<jk-button v-if="pageType !== 'detail'" size="mini" type="success" @click="onSelectReworkNoticeBtn(scope, 1)">包装返工单</jk-button>
								</div>
							</el-popover>
						</div>
					</template>
				</vxe-column>
				<vxe-column title="批号" align="left" field="batchCode" :width="100"></vxe-column>
				<vxe-column title="纸管颜色" align="left" field="paperTubeList" :width="80">
					<template slot-scope="scope">
						<div class="flex-between-center">
							<div style="display: flex">
								<div>{{ scope.row.matePaperColor || paperTubeList(scope.row.paperTubeList) }}</div>
							</div>
							<el-popover title="纸管颜色" content="" placement="bottom" trigger="click">
								<div slot="reference" class="drag-info-icon" style="color: #2d8cf0;font-size: 13px;">
									<div v-if="pageType !== 'detail'" class="el-icon-edit-outline operation-style" @click="obEliminateBtn"></div>
								</div>
								<div style="display:flex; justify-content: center; align-items: center; margin-right: 5px;">
									<el-select v-model="paperTubeId" size="mini" @change="onPaperTubeChange($event, scope.rowIndex, scope.row.paperTubeList)">
										<el-option
											v-for="item in scope.row.paperTubeList"
											:key="item.id"
											:label="item.name"
											:value="item.id"
										>
										</el-option>
									</el-select>
								</div>
							</el-popover>
						</div>
					</template>
				</vxe-column>
				<vxe-column title="腰绳颜色" align="left" field="waistPopeList" :width="80">
					<template slot-scope="scope">
						<div class="flex-between-center">
							<div style="display: flex">
								<span>{{ scope.row.mateWaistColor || waistPopeList(scope.row.waistPopeList) }}</span>
							</div>
							<el-popover title="腰绳颜色" content="" placement="bottom" trigger="click">
								<div slot="reference" class="drag-info-icon" style="color: #2d8cf0;font-size: 13px;">
									<div v-if="pageType !== 'detail'" class="el-icon-edit-outline operation-style" @click="obEliminateBtn"></div>
								</div>
								<div style="display:flex; justify-content: center; align-items: center; margin-right: 5px;">
									<el-select v-model="waistPopeId" size="mini" @change="onWaistPopeChange($event, scope.rowIndex, scope.row.waistPopeList)">
										<el-option
											v-for="item in scope.row.waistPopeList"
											:key="item.id"
											:label="item.name"
											:value="item.id"
										>
										</el-option>
									</el-select>
								</div>
							</el-popover>
						</div>
					</template>
				</vxe-column>
				<vxe-column title="标签颜色" align="left" field="unitPrice" :width="80">
					<template slot-scope="scope">
						<div class="flex-between-center">
							<div style="display: flex">
								<span>{{ scope.row.mateLabelColor || labelColorList(scope.row.labelColorList) }}</span>
							</div>
							<el-popover title="标签颜色" content="" placement="bottom" trigger="click">
								<div slot="reference" class="drag-info-icon" style="color: #2d8cf0;font-size: 13px;">
									<div v-if="pageType !== 'detail'" class="el-icon-edit-outline operation-style" @click="obEliminateBtn"></div>
								</div>
								<div style="display:flex; justify-content: center; align-items: center; margin-right: 5px;">
									<el-select v-model="labelColorId" size="mini" @change="onLabelColorChange($event, scope.rowIndex, scope.row.labelColorList)">
										<el-option
											v-for="item in scope.row.labelColorList"
											:key="item.id"
											:label="item.name"
											:value="item.id"
										>
										</el-option>
									</el-select>
								</div>
							</el-popover>
						</div>
					</template>
				</vxe-column>
				<vxe-column title="尽头" align="center" field="ifAllClose" :width="70">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{
							scope.row.ifAllClose ? '是' : '否'
						}}</span>
						<el-checkbox
							v-else
							v-model="scope.row.ifAllClose"
							size="mini"
							placeholder=""
							@change="onCheckboxChange($event, scope)"
						>是
						</el-checkbox>
					</template>
				</vxe-column>
				<vxe-column title="接班数" align="right" field="lastClassRemainderNumber" :width="80">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{
							scope.row.lastClassRemainderNumber
						}}</span>
						<jk-number-input v-else v-model="scope.row.lastClassRemainderNumber" size="mini" placeholder="" @change="onPackNumChange($event, scope.row, scope.rowIndex)" />
					</template>
				</vxe-column>
				<vxe-column title="系统读数" align="right" field="systemPackNum" :width="80"></vxe-column>
				<vxe-column title="本班报工包数" align="right" field="packNum" :width="110">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.packNum }}</span>
						<jk-number-input
							v-else
							v-model="scope.row.packNum"
							size="mini"
							placeholder=""
							@change="onPackNumChange($event, scope.row, scope.rowIndex)"
						/>
					</template>
				</vxe-column>
				<vxe-column title="本班交班数" align="right" field="thisClassRemainderNumber" :width="90">
				</vxe-column>
				<vxe-column title="零包数" align="right" field="remainderNumber" :width="90">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.remainderNumber }}</span>
						<jk-number-input
							v-else
							v-model="scope.row.remainderNumber"
							:disabled="!scope.row.ifAllClose"
							size="mini"
							placeholder=""
						/>
					</template>
				</vxe-column>
				<vxe-column title="活码(个)" align="right" field="liveCodeNum" :width="90">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.liveCodeNum }}</span>
						<jk-number-input
							v-else
							v-model="scope.row.liveCodeNum"
							:disabled="!scope.row.ifAllClose"
							size="mini"
							placeholder=""
						/>
					</template>
				</vxe-column>
				<vxe-column title="活码(公斤)" align="right" field="liveCode" :width="100">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.liveCode }}</span>
						<jk-number-input
							v-else
							v-model="scope.row.liveCode"
							:disabled="!scope.row.ifAllClose"
							size="mini"
							placeholder=""
						/>
					</template>
				</vxe-column>
				<vxe-column :visible="pageType !== 'detail'" title="操作" align="center" field="productName" :width="50">
					<template slot-scope="scope">
						<div class="el-icon-remove operation-style" @click="ruleForm.itemList.splice(scope.rowIndex, 1)"></div>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>

		<radio-select-notice-order-dialog
			:dialog-state="selectNoticeOrderDialogState"
			@on-visible-change="onVisibleChangeOfSelectNoticeOrderDialog"
			@on-confirm="onConfirmBtnOfSelectDialog"
		></radio-select-notice-order-dialog>
		<!--    改包装-->
		<radio-select-chang-notice-dialog
			:dialog-state="selectChangeNoticeDialogState"
			@on-visible-change="onVisibleChangeOfSelectChangeNoticeDialog"
			@on-confirm="onConfirmBtnChangeNoticeSelectDialog"
		></radio-select-chang-notice-dialog>
		<!--    返工单-->
		<radio-select-rework-notice-dialog
			:dialog-state="selectReworkNoticeDialogState"
			@on-visible-change="onVisibleChangeOfSelectReworkNoticeDialog"
			@on-confirm="onConfirmBtnReworkNoticeSelectDialog"
		></radio-select-rework-notice-dialog>
	</jk-dialog>
</template>

<script>
    import radioSelectNoticeOrderDialog from './components/radio-select-notice-dialog';
    import radioSelectChangNoticeDialog from './components/radio-select-chang-notice-dialog';
    import radioSelectReworkNoticeDialog from './components/radio-select-rework-notice-dialog';
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        productionPackPrdReportCreate,
        productionPackPrdReportUpdate,
        productionPackPrdReportGet,
        productionPackPrdReportGetData
    } from '../../../../api/production/package';
    import remoteSearchProductInput from '../../../technology/order/components/remote-search-product-input';
    import { workforcemanagementScheduleList } from '../../../../api/schedule/scheduling';
    import { formatDate, formatTime, tipsBar } from '../../../../utils/jk/jk-tool';
    import XEUtils from 'xe-utils';
    import { mathJsAdd } from '../../../../utils/jk/jk-cals';
    import remoteSearchBatchCodeInput
        from '../../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
    import { machinemanagerMachinePage } from '../../../../api/machine/machineArchives';
    import repairStateBar from './components/repair-state-bar.vue';
    import checkboxPopover from '../../../production/order/components/form-box/checkbox-popover.vue';
    import getTubeColor from '../../../production/foreSpinPrd/foreSpinningPlan/components/form-box/get-tube-color';

    export default {
        mixins: [calHeight, getTubeColor],
        components: {
            checkboxPopover,
            repairStateBar,
            radioSelectNoticeOrderDialog,
            remoteSearchBatchCodeInput,
            remoteSearchProductInput,
            radioSelectChangNoticeDialog,
            radioSelectReworkNoticeDialog
        },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                selectMachineId: null,
                machineList: [],
                exportLoading: false,
                paperTubeId: null,
                waistPopeId: null,
                labelColorId: null,
                selectNoticeOrderDialogState: false,
                selectChangeNoticeDialogState: false,
                selectReworkNoticeDialogState: false,
                totalNum: 0,
                scheduleShiftList: [],
                tableLoading: false,
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                updateLoading: false,
                ruleForm: {
                    'allNum': 0,
                    'allQty': 0,
                    'auditId': 0,
                    'auditName': '',
                    'auditOpinion': '',
                    'auditState': 0,
                    'auditTime': '',
                    'machineId': null,
                    'machineCode': '',
                    'machineName': '',
                    'belongDate': '',
                    'code': '',
                    'totalNum': 0,
                    'generateType': 0,
                    'itemList': [],
                    'remark': '',
                    'scheduleShiftId': null,
                    'shiftId': null,
                    'shiftName': '',
                    'workshopId': null,
                    'workshopName': ''
                },
                rules: {
                    workshopId: [{ required: true, trigger: 'change' }],
                    belongDate: [{ required: true, trigger: 'change' }],
                    scheduleShiftId: [{ required: true, trigger: 'change' }],
                    machineId: [{ required: true, trigger: 'change' }]
                },
                editRowIndex: null,
                operationType: '',
                paperTubeIdList: []
            };
        },
        methods: {
            // 纸管颜色
            paperTubeList(item) {
                if (item && item.length) {
                    let trueName = '';
                    let falseName = '';
                    for (const x of item) {
                        if (x.auditState === true) {
                            trueName = x.name;
                            break; // 找到第一个 true 名字后退出循环
                        }
                    }
                    for (const x of item) {
                        if (x.auditState === false) {
                            falseName = x.name;
                            break; // 找到第一个 false 名字后退出循环
                        }
                    }
                    return trueName || falseName;
                }
                return '';
            },
            // 腰绳颜色
            waistPopeList(item) {
                if (item && item.length) {
                    let trueName = '';
                    let falseName = '';
                    for (const x of item) {
                        if (x.auditState === true) {
                            trueName = x.name;
                            break; // 找到第一个 true 名字后退出循环
                        }
                    }
                    for (const x of item) {
                        if (x.auditState === false) {
                            falseName = x.name;
                            break; // 找到第一个 false 名字后退出循环
                        }
                    }
                    return trueName || falseName;
                }
                return '';
            },
            // 标签颜色
            labelColorList(item) {
                if (item && item.length) {
                    let trueName = '';
                    let falseName = '';
                    for (const x of item) {
                        if (x.auditState === true) {
                            trueName = x.name;
                            break; // 找到第一个 true 名字后退出循环
                        }
                    }
                    for (const x of item) {
                        if (x.auditState === false) {
                            falseName = x.name;
                            break; // 找到第一个 false 名字后退出循环
                        }
                    }
                    return trueName || falseName;
                }
                return '';
            },
            obEliminateBtn() {
                this.paperTubeId = null;
                this.waistPopeId = null;
                this.labelColorId = null;
            },
            onWaistPopeChange(e, index, waistPopeList) {
                waistPopeList.forEach(x => {
                    if (x.id === e) {
                        this.$set(this.ruleForm.itemList[index], 'mateWaistColor', x.name);
                    }
                });
                document.body.click();
            },
            onPaperTubeChange(e, index, paperTubeList) {
                paperTubeList.forEach(x => {
                    if (x.id === e) {
                        this.$set(this.ruleForm.itemList[index], 'matePaperColor', x.name);
                    }
                });
                document.body.click();
            },
            onLabelColorChange(e, index, labelColorList) {
                labelColorList.forEach(x => {
                    if (x.id === e) {
                        this.$set(this.ruleForm.itemList[index], 'mateLabelColor', x.name);
                    }
                });
                document.body.click();
            },
            onSelectMachineChange(e) {
                if (e) {
                    const item = this.machineList.find(x => x.id === e) || {};
                    const has = this.ruleForm.itemList.some(x => x.machineId === e);
                    if (!has) {
                        this.ruleForm.itemList.push({
                            machineId: item.id,
                            machineCode: item.code,
                            machineName: item.name,
                            ifAllClose: false,
                            lastClassRemainderNumber: 0,
                            systemPackNum: 0,
                            packNum: 0,
                            thisClassRemainderNumber: 0,
                            remainderNumber: 0,
                            liveCodeNum: 0,
                            liveCode: 0,

                            batchId: null,
                            batchCode: null,
                            productId: null,
                            productCode: null,
                            productName: null,
                            productOrderCode: null,
                            productOrderId: null,
                            paperTubeList: [],
                            waistPopeList: [],
                            labelColorList: []
                        });
                    } else {
                        tipsBar(this, 'custom', 'warning', '机台已存在!');
                    }
                }
            },
            /** 导出按钮操作 */
            onReportBtn() {
                  import('@/vendor/Export2Excel').then(excel => {
                        const tHeader = [
                          '机台', '品种', '批号', '纸管颜色', '腰绳颜色',
                          '标签颜色', '尽头', '接班数', '系统读数', '本班报工包数',
                          '本班交班数', '零包数', '活码(个)', '活码(公斤)'
                        ];
                        const filterVal = [
                          'machineName', 'productName', 'batchCode', 'paperTubeList', 'waistPopeList',
                          'labelColorList', 'ifAllClose', 'lastClassRemainderNumber', 'systemPackNum', 'packNum',
                          'thisClassRemainderNumber', 'remainderNumber', 'liveCodeNum', 'liveCode'
                        ];
                        const list = JSON.parse(JSON.stringify(this.ruleForm.itemList));
                        list.forEach((item) => {
                          item.ifAllClose = item.ifAllClose ? '是' : '否';
                          item.paperTubeList = item.paperTubeList && item.paperTubeList.length ? item.paperTubeList.map(x => x.auditState === true ? x.name : '').filter(item => item !== '').join(',') : '';
                          item.waistPopeList = item.waistPopeList && item.waistPopeList.length ? item.waistPopeList.map(x => x.auditState === true ? x.name : '').filter(item => item !== '').join(',') : '';
                          item.labelColorList = item.labelColorList && item.labelColorList.length ? item.labelColorList.map(x => x.auditState === true ? x.name : '').filter(item => item !== '').join(',') : '';
                        });
                        // 合计项
                        const totalItem = {};
                        filterVal.forEach((x, idx) => {
                          totalItem[x] = this.$refs.jkTable.$refs.xTable.getTableData().footerData[0][idx];
                        });
                        list.push(totalItem);
                        const data = list.map(v => filterVal.map(j => {
                          return v[j];
                        }));
                        excel.export_json_to_excel({
                          header: tHeader,
                          data,
                          filename: `打包报工-${this.ruleForm.belongDate + this.ruleForm.shiftName}`,
                          autoWidth: true,
                          bookType: 'xlsx'
                        });
                  });
            },
            onPackNumChange(e, row, index) {
                const num = mathJsAdd(row.packNum || 0, row.lastClassRemainderNumber || 0);
                if (this.ruleForm.itemList[index].ifAllClose) {
                    this.$set(this.ruleForm.itemList[index], 'remainderNumber', num % 40);
                    this.$set(this.ruleForm.itemList[index], 'thisClassRemainderNumber', 0);
                } else {
                    this.$set(this.ruleForm.itemList[index], 'thisClassRemainderNumber', num % 40);
                    this.$set(this.ruleForm.itemList[index], 'remainderNumber', 0);
                }
            },
            onSelectBatchCodeBtn(scope, type) {
                this.operationType = type;
                if (type === 0) {
                    // 记录该打包机最后一条记录的索引，用于添加品种时需要插入的位置
                    let idx = null;
                    this.ruleForm.itemList.forEach((machineItem, machineIndex) => {
                        if (machineItem.machineName === scope.row.machineName) {
                            idx = machineIndex;
                        }
                    });
                    this.editRowIndex = idx;
                } else {
                    this.editRowIndex = scope.rowIndex;
                }
                this.selectNoticeOrderDialogState = true;
            },
            // 返工单
            onSelectReworkNoticeBtn(scope, type) {
                this.operationType = type;
                if (type === 0) {
                    // 记录该打包机最后一条记录的索引，用于添加品种时需要插入的位置
                    let idx = null;
                    this.ruleForm.itemList.forEach((machineItem, machineIndex) => {
                        if (machineItem.machineName === scope.row.machineName) {
                            idx = machineIndex;
                        }
                    });
                    this.editRowIndex = idx;
                } else {
                    this.editRowIndex = scope.rowIndex;
                }
                this.selectReworkNoticeDialogState = true;
            },
            // 改包装
            onSelectChangeNoticeBtn(scope, type) {
                this.operationType = type;
                if (type === 0) {
                    // 记录该打包机最后一条记录的索引，用于添加品种时需要插入的位置
                    let idx = null;
                    this.ruleForm.itemList.forEach((machineItem, machineIndex) => {
                        if (machineItem.machineName === scope.row.machineName) {
                            idx = machineIndex;
                        }
                    });
                    this.editRowIndex = idx;
                } else {
                    this.editRowIndex = scope.rowIndex;
                }
                this.selectChangeNoticeDialogState = true;
            },
            onConfirmBtnOfSelectDialog(e) {
                const paperTubeList = e.orderBatch ? e.orderBatch.paperTubeList : [];
                const waistPopeList = e.orderBatch ? e.orderBatch.waistPopeList : [];
                const labelColorList = e.orderBatch ? e.orderBatch.labelColorList : [];
                if (this.operationType === 0) {
                    this.ruleForm.itemList.splice(this.editRowIndex + 1, 0, {
                        machineId: this.ruleForm.itemList[this.editRowIndex].machineId,
                        machineCode: this.ruleForm.itemList[this.editRowIndex].machineCode,
                        machineName: this.ruleForm.itemList[this.editRowIndex].machineName,
                        ifAllClose: false,
                        lastClassRemainderNumber: 0,
                        systemPackNum: 0,
                        packNum: 0,
                        thisClassRemainderNumber: 0,
                        remainderNumber: 0,
                        liveCodeNum: 0,
                        liveCode: 0,
                        type: 0,

                        batchId: e.batchId,
                        batchCode: e.batchCode,
                        productId: e.productId,
                        productCode: e.productCode,
                        productName: e.productName,
                        productOrderCode: e.productOrderCode,
                        productOrderId: e.productOrderId,
                        paperTubeList: paperTubeList,
                        waistPopeList: waistPopeList,
                        labelColorList: labelColorList
                    });
                } else {
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'batchId', e.batchId);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'batchCode', e.batchCode);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productId', e.productId);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productCode', e.productCode);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productName', e.productName);

                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productionOrderCode', e.productOrderCode);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productionOrderId', e.productOrderId);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'type', 0);

                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'paperTubeList', paperTubeList);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'waistPopeList', waistPopeList);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'labelColorList', labelColorList);
                }
                this.selectNoticeOrderDialogState = false;
            },
            // 改包装
            onConfirmBtnChangeNoticeSelectDialog(e) {
                const paperTubeList = e ? e.paperTubeList : [];
                const waistPopeList = e ? e.waistPopeList : [];
                const labelColorList = e ? e.labelColorList : [];
                if (this.operationType === 0) {
                    this.ruleForm.itemList.splice(this.editRowIndex + 1, 0, {
                        machineId: this.ruleForm.itemList[this.editRowIndex].machineId,
                        machineCode: this.ruleForm.itemList[this.editRowIndex].machineCode,
                        machineName: this.ruleForm.itemList[this.editRowIndex].machineName,
                        ifAllClose: false,
                        lastClassRemainderNumber: 0,
                        systemPackNum: 0,
                        packNum: e.packQty,
                        thisClassRemainderNumber: 0,
                        remainderNumber: 0,
                        liveCodeNum: 0,
                        liveCode: 0,
                        type: 1,

                        batchId: e.batchId,
                        batchCode: e.batchCode,
                        productId: e.productId,
                        productCode: e.productCode,
                        productName: e.productName,
                        changeProductRecordId: e.id,
                        productOrderCode: e.productOrderCode,
                        productOrderId: e.productOrderId,
                        paperTubeList: paperTubeList,
                        waistPopeList: waistPopeList,
                        labelColorList: labelColorList
                    });
                } else {
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'batchId', e.batchId);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'batchCode', e.batchCode);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productId', e.productId);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productCode', e.productCode);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productName', e.productName);

                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productionOrderCode', e.productOrderCode);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productionOrderId', e.productOrderId);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'changeProductRecordId', e.id);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'type', 1);

                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'paperTubeList', paperTubeList);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'waistPopeList', waistPopeList);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'labelColorList', labelColorList);
                }
                this.selectChangeNoticeDialogState = false;
            },
            // 返工单
            onConfirmBtnReworkNoticeSelectDialog(e) {
                const paperTubeList = e.orderBatch ? e.orderBatch.paperTubeList : [];
                const waistPopeList = e.orderBatch ? e.orderBatch.waistPopeList : [];
                const labelColorList = e.orderBatch ? e.orderBatch.labelColorList : [];
                if (this.operationType === 0) {
                    this.ruleForm.itemList.splice(this.editRowIndex + 1, 0, {
                        machineId: this.ruleForm.itemList[this.editRowIndex].machineId,
                        machineCode: this.ruleForm.itemList[this.editRowIndex].machineCode,
                        machineName: this.ruleForm.itemList[this.editRowIndex].machineName,
                        ifAllClose: false,
                        lastClassRemainderNumber: 0,
                        systemPackNum: 0,
                        packNum: 0,
                        thisClassRemainderNumber: 0,
                        remainderNumber: 0,
                        liveCodeNum: 0,
                        liveCode: 0,
                        type: 2,

                        batchId: e.batchId,
                        batchCode: e.batchCode,
                        productId: e.productId,
                        productCode: e.productCode,
                        productName: e.productName,
                        changeProductRecordId: e.id,
                        productOrderCode: e.productOrderCode,
                        productOrderId: e.productOrderId,
                        paperTubeList: paperTubeList,
                        waistPopeList: waistPopeList,
                        labelColorList: labelColorList
                    });
                } else {
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'batchId', e.batchId);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'batchCode', e.batchCode);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productId', e.productId);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productCode', e.productCode);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productName', e.productName);

                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productionOrderCode', e.productOrderCode);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'productionOrderId', e.productOrderId);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'changeProductRecordId', e.id);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'type', 2);

                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'paperTubeList', paperTubeList);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'waistPopeList', waistPopeList);
                    this.$set(this.ruleForm.itemList[this.editRowIndex], 'labelColorList', labelColorList);
                }
                this.selectReworkNoticeDialogState = false;
            },
            onVisibleChangeOfSelectNoticeOrderDialog(e) {
                this.selectNoticeOrderDialogState = e;
            },
            // 返工单
            onVisibleChangeOfSelectReworkNoticeDialog(e) {
                this.selectReworkNoticeDialogState = e;
            },
            // 改包装
            onVisibleChangeOfSelectChangeNoticeDialog(e) {
                this.selectChangeNoticeDialogState = e;
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const prevRow = visibleData[_rowIndex - 1];
                let nextRow = visibleData[_rowIndex + 1];
                if (column.property === 'machineName') {
                    if (prevRow && prevRow.machineName === row.machineName) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow.machineName === row.machineName) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            footerMethod({ columns, data }) {
                const keys = ['liveCodeNum', 'liveCode', 'remainderNumber', 'thisClassRemainderNumber', 'thisClassRemainderNumber', 'packNum', 'lastClassRemainderNumber'];
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计';
                        }
                        if (keys.includes(column.field)) {
                            return XEUtils.sum(data, column.field);
                        }
                        return null;
                    })
                ];
            },
            onCheckboxChange(e, scope) {
                if (e) {
                    this.$set(this.ruleForm.itemList[scope.rowIndex], 'remainderNumber', this.ruleForm.itemList[scope.rowIndex].thisClassRemainderNumber);
                    this.$set(this.ruleForm.itemList[scope.rowIndex], 'thisClassRemainderNumber', 0);
                } else {
                    this.$set(this.ruleForm.itemList[scope.rowIndex], 'thisClassRemainderNumber', this.ruleForm.itemList[scope.rowIndex].remainderNumber);
                    this.$set(this.ruleForm.itemList[scope.rowIndex], 'remainderNumber', 0);
                    this.$set(this.ruleForm.itemList[scope.rowIndex], 'liveCode', 0);
                    this.$set(this.ruleForm.itemList[scope.rowIndex], 'liveCodeNum', 0);
                }
            },
            onWorkshopChange() {
                this.$set(this.ruleForm, 'itemList', []);
                this.$set(this.ruleForm, 'scheduleShiftId', null);
                this.$set(this.ruleForm, 'shiftId', null);
                this.$set(this.ruleForm, 'shiftCode', null);
                this.$set(this.ruleForm, 'shiftName', null);
                this.scheduleShiftList = [];
                this.getDateScheduleShiftOptionRequest();

                this.$set(this.ruleForm, 'machineId', null);
                this.$set(this.ruleForm, 'machineCode', null);
                this.$set(this.ruleForm, 'machineName', null);
            },
            getDateScheduleShiftOptionRequest() {
                if (this.ruleForm.workshopId && this.ruleForm.belongDate) {
                    return workforcemanagementScheduleList({
                        belongDate: [this.ruleForm.belongDate, this.ruleForm.belongDate],
                        workshopId: this.ruleForm.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData && resData.length) {
                                this.scheduleShiftList = resData[0].scheduleShiftList;
                            }
                        }
                    });
                }
            },
            onDateChange() {
                this.$set(this.ruleForm, 'scheduleShiftId', null);
                this.$set(this.ruleForm, 'shiftId', null);
                this.$set(this.ruleForm, 'shiftCode', null);
                this.$set(this.ruleForm, 'shiftName', null);
                this.$set(this.ruleForm, 'itemList', []);
                this.scheduleShiftList = [];
                this.getDateScheduleShiftOptionRequest();
            },
            onScheduleShiftChange(e) {
                let item = {};
                if (e) {
                    item = this.scheduleShiftList.find(x => x.id === e);
                } else {
                    item = {
                        id: null,
                        shiftId: null,
                        shiftCode: null,
                        shiftName: null,
                        scheduleId: null
                    };
                }
                this.$set(this.ruleForm, 'itemList', []);
                this.$set(this.ruleForm, 'scheduleId', item.scheduleId);
                this.$set(this.ruleForm, 'scheduleShiftId', item.id);
                this.$set(this.ruleForm, 'shiftId', item.shiftId);
                this.$set(this.ruleForm, 'shiftCode', item.shiftCode);
                this.$set(this.ruleForm, 'shiftName', item.shiftName);
                this.getPackageRecordListRequest();
            },
            // 获取该班次的打包记录
            getPackageRecordListRequest() {
                if (!this.ruleForm.scheduleShiftId) return;
                this.updateLoading = true;
                productionPackPrdReportGetData({
                    scheduleShiftId: this.ruleForm.scheduleShiftId
                }).then(res => {
                    this.updateLoading = false;
                    if (res.data.status === 200) {
                        this.$set(this.ruleForm, 'itemList', res.data.res || []);
                    }
                });
            },
            onDeleteBtn(scope) {
                this.ruleForm.itemList.splice(scope.rowIndex, 1);
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;

                if (!this.dataId) {
                    const shiftItem = this.scheduleShiftList.find(x => x.id === params.scheduleShiftId) || {};
                    params.shiftId = shiftItem.shiftId;
                    params.shiftCode = shiftItem.shiftCode;
                    params.shiftName = shiftItem.shiftName;
                }

                if (!this.dataId) {
                    // params.auditState = 1;
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? productionPackPrdReportCreate : productionPackPrdReportUpdate;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionPackPrdReportGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.itemList = resData.itemList || [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getMachineListRequest() {
                return machinemanagerMachinePage({
                    processCode: 'DB',
                    auditState: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.machineList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.workshopList = this.$store.state.user.userWorkshop.workshopList || [];
                const item = this.workshopList.find(x => x.code.toUpperCase() === 'ZL') || {};
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'workshopId', item.id);
                    this.$set(this.ruleForm, 'workshopCode', item.code);
                    this.$set(this.ruleForm, 'workshopName', item.name);
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                    this.$set(this.ruleForm, 'auditTime', formatTime(Date.now()));
                }
                this.showLoading = true;
                await this.getMachineListRequest();
                await this.getDateScheduleShiftOptionRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            'ruleForm.itemList': {
                handler() {
                    this.totalNum = 0;
                    this.ruleForm.itemList.forEach(x => {
                        this.totalNum = mathJsAdd(x.packNum || 0, this.totalNum);
                        if (x.liveCodeNum) {
                            this.totalNum = mathJsAdd(1, this.totalNum);
                        }
                    });
                },
                deep: true
            },
            ruleForm: {
                handler() {
                    this.$nextTick(() => {
                        this.$refs.jkTable.$refs.xTable.updateFooter();
                    });
                },
                deep: true
            },
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.operation-style {
  color: #2d8cf0;
  cursor: pointer;
}
</style>
